<template>
  <div class="category-container">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-input
          v-model="data.name"
          prefix-icon="Search"
          placeholder="请输入分类名称"
          clearable
          class="search-input"
          @keyup.enter="load"
      ></el-input>
      <div class="search-buttons">
        <el-button type="primary" @click="load">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus/>
        </el-icon>
        <span>新增分类</span>
      </el-button>
      <el-button type="danger" :disabled="!data.ids.length" @click="delBatch">
        <el-icon>
          <Delete/>
        </el-icon>
        <span>批量删除</span>
      </el-button>
    </div>

    <!-- 数据表格 -->
    <div class="data-table">
      <el-table
          :data="data.tableData"
          @selection-change="handleSelectionChange"
          stripe
          style="width: 100%"
          empty-text="暂无分类数据"
      >
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column type="index" label="序号" width="80" align="center"/>

        <el-table-column prop="name" label="分类名称" width="250"/>

        <el-table-column prop="picurl" label="分类壁纸" width="250" align="center">
          <template v-slot="scope">
            <el-image
                v-if="scope.row.picurl"
                :src="scope.row.picurl"
                :preview-src-list="[scope.row.picurl]"
                preview-teleported
                class="category-image"
            >
              <template #error>
                <div class="image-error">
                  <el-icon>
                    <Picture/>
                  </el-icon>
                </div>
              </template>
            </el-image>
            <span v-else class="no-image">暂无图片</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="150" fixed="right" align="center">
          <template v-slot="scope">
            <el-button
                type="primary"
                size="small"
                :icon="Edit"
                @click="handleEdit(scope.row)"
                class="action-btn"
            ></el-button>
            <el-button
                type="danger"
                size="small"
                :icon="Delete"
                @click="del(scope.row.id)"
                class="action-btn"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination" v-if="data.total">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next"
          :total="data.total"
          @size-change="load"
          @current-change="load"
      />
    </div>

    <el-dialog title="分类信息" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="name" label="名称">
          <el-input v-model="data.form.name" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item prop="picurl" label="分类壁纸">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :on-success="handleFileUpload"
              list-type="picture"
          >
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>

import {reactive} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue";

const baseUrl = import.meta.env.VITE_BASE_URL

const data = reactive({
  formVisible: false,
  form: {},
  tableData: [],
  pageNum: 1,
  pageSize: 5,
  total: 0,
  name: null,
  ids: []
})

const load = () => {
  request.get('/category/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || []
      data.total = res.data?.total
    }
  })
}
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}
const add = () => {
  request.post('/category/add', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const update = () => {
  request.put('/category/update', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      data.formVisible = false
      load()
    }
  })
}

const save = () => {
  data.form.id ? update() : add()
}

const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/category/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功")
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
    console.error(err)
  })
}
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据")
    return
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete("/category/delete/batch", {data: data.ids}).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
    console.error(err)
  })
}
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id)
}

const handleFileUpload = (res) => {
  data.form.picurl = res.data
}

const reset = () => {
  data.name = null
  load()
}

load()
</script>

<style scoped>
.category-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.search-input {
  width: 300px;
  margin-right: 16px;
}

.search-buttons {
  display: flex;
  gap: 8px;
}

.action-bar {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  display: flex;
  gap: 12px;
}

.data-table {
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.category-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  object-fit: cover;
}

.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 50px;
  height: 50px;
  background: #f5f5f5;
  border-radius: 4px;
  color: #999;
}

.no-image {
  color: #999;
  font-size: 12px;
}

.action-btn {
  margin: 0 4px;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 16px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}
</style>